package com.example.rabbitmq01.rpc;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;

public class Client {
    private static ConnectionFactory factory;
    private static Connection connection;
    private static Channel channel;

    private static final String QUEUE = "queue";

    //用来存放lambda的计算结果
    private static int ret;

    public static void main(String[] args) throws IOException, TimeoutException, ExecutionException, InterruptedException {
        factory = new ConnectionFactory();
        connection = factory.newConnection();
        channel = connection.createChannel();

        //创建队列
        channel.queueDeclare(QUEUE, false, false, false, null);

        //这里让服务器计算一下sum(1, num)
        int ans = Integer.parseInt(rpcCall(100));

        System.out.println("计算结果：" + ans);
    }

    private static String rpcCall(int num) throws IOException, ExecutionException, InterruptedException {
        //生成本次调用的唯一请求ID
        String corrID = UUID.randomUUID().toString();

        //生成响应回调队列
        String replyQueueName = channel.queueDeclare().getQueue();

        //配置消息的属性
        AMQP.BasicProperties basicProperties = new AMQP.BasicProperties
                .Builder()
                .correlationId(corrID)
                .replyTo(replyQueueName)
                .build();

        //发送消息
        channel.basicPublish("",  QUEUE, basicProperties, ("" + num).getBytes());

        CompletableFuture<String> response = new CompletableFuture<>();

        //消费计算的消息
        channel.basicConsume(replyQueueName, true, (consumerTag, delivery) -> {
                if(delivery.getProperties().getCorrelationId().equals(corrID)){
                    response.complete(new String(delivery.getBody()));
                }
        }, (consumerTag) -> {

        });

        return response.get();
    }
}
